package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
)

var mqttOBJ MQTT.Client

var messagePubHandler MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
	// fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
}

var connectHandler MQTT.OnConnectHandler = func(client MQTT.Client) {
	// 复制全局变量页面调用使用
	fmt.Println("Mqtt connect Connected")
	// client.Subscribe("your_subscribe_topic", 0, nil)

}

var connectLostHandler MQTT.ConnectionLostHandler = func(client MQTT.Client, err error) {
	client.Connect()
}

func mqttRun(done chan struct{}) {
	// 创建一个 MQTT 选项对象
	opts := MQTT.NewClientOptions()
	// opts.AddBroker("tcp://broker.emqx.io:1883")
	opts.AddBroker("tcp://192.168.31.122:1883")
	opts.SetClientID("go-mqtt-client")
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	// 创建一个 MQTT 客户端
	mqttOBJ = MQTT.NewClient(opts)
	// 连接到 MQTT 代理
	token := mqttOBJ.Connect()
	token.Wait()
	if token.Error() != nil {
		fmt.Println("连接 MQTT 代理失败：", token.Error())
		return
	}
	close(done)

}

func main() {

	done := make(chan struct{})
	go mqttRun(done)
	<-done
	time.Sleep(1 * time.Second)

	reader := bufio.NewReader(os.Stdin)
	fmt.Println("功能目录\n 1. 广州招募\n 2. 广州补录")
	fmt.Println("请选择需要重启的脚本（一天只能使用一次）：")
	input, err := reader.ReadString('\n')
	input = input[:len(input)-2]
	if err != nil {
		fmt.Println("读取输入错误：", err)
		return
	}

	switch strings.TrimRight(input, "\r") {
	case "1":
		{
			token := mqttOBJ.Publish("server/guangzhou/zhaomu", 0, false, "过来重启你了")
			token.Wait()
			if token.Error() != nil {
				fmt.Println("发布消息失败：", token.Error())
			} else {
				fmt.Println("消息发布成功")
				println("程序正在重启中，请稍后查看。")
			}
			break

		}
	case "2":
		{
			token := mqttOBJ.Publish("server/guangzhou/bulu", 0, false, "过来重启你了")
			token.Wait()
			if token.Error() != nil {
				fmt.Println("发布消息失败：", token.Error())
			} else {
				fmt.Println("消息发布成功")
				println("程序正在重启中，请稍后查看。")
			}
			break
		}
	default:
		println("请输入正确选择。")
	}

	for {

	}
}
